﻿using Castle.Core;
using Castle.MicroKernel.Facilities;

namespace MessagingWPF.Infrastructure
{
	/// <summary>
	/// A facility for automatic subscribing through the windsor container.
	/// </summary>
	public class SubscriptionFacility : AbstractFacility
	{
		private ISubscriptionManager _SubscriptionManager;

		/// <summary>
		/// Initializes this facility.
		/// </summary>
		protected override void Init()
		{
			Kernel.ComponentModelCreated += OnComponentModelCreated;
			Kernel.ComponentCreated += OnComponentCreated;
			Kernel.ComponentDestroyed += OnComponentDestroyed;
		}

		private void OnComponentDestroyed(ComponentModel model, object instance)
		{
			if (_SubscriptionManager != null)
			{
				_SubscriptionManager.Unsubscribe(instance);
			}
		}

		private void OnComponentCreated(ComponentModel model, object instance)
		{
			if (instance is ISubscriptionManager)
			{
				_SubscriptionManager = (ISubscriptionManager) instance;
			}
			else if (_SubscriptionManager != null)
			{
				_SubscriptionManager.Subscribe(instance);
			}
		}

		private void OnComponentModelCreated(ComponentModel model)
		{
			if (_SubscriptionManager != null)
			{
				_SubscriptionManager.Subscribe(model.Implementation);
			}
		}
	}
}